import { Directive } from '@angular/core';
import { AsyncValidator, NG_ASYNC_VALIDATORS, AbstractControl, ValidationErrors } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { UserService } from '../user.service';
import { Result } from 'src/app/common/result.interface';
@Directive({
  selector: '[appPhoneValidate]',
  providers: [
    { provide: NG_ASYNC_VALIDATORS, useExisting: PhoneValidateDirective, multi: true }
  ]
})
export class PhoneValidateDirective implements AsyncValidator {

  constructor(private us: UserService) { }
  validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
    return this.us.validatePhone(control.value).pipe(
      map((r: Result<string>) => {
        return r.success ? null : { validatePhone: true };
      }),
      catchError(e => of({ validatePhone: true }))
    );

  }






}
